package fantasy;

import java.io.IOException;
import java.util.Properties;

import javax.jdo.PersistenceManager;

import net.oauth.OAuthException;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;
import com.simpleyql.QueryResult;

public class YahooApiQuery {
	
	private String user;
	
	private String baseurl;
	
	private String yahoo_consumer_key;
	
	private String yahoo_consumer_secret;
	
	private Api api;
	
	public YahooApiQuery() throws IOException {


        Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("fantasy.properties"));
		
		this.baseurl = props.getProperty("application.baseurl");
		this.yahoo_consumer_key = props.getProperty("oauth.consumerkey");
		this.yahoo_consumer_secret = props.getProperty("oauth.consumersecret");
				
		this.api = ApiFactory.getApiInstance(
				this.yahoo_consumer_key,
				this.yahoo_consumer_secret,
	            baseurl + "/simpleyqlcallback/",
	            false, null);

	}
	
	public String query(String query) {

        // Initiate Persistence Manager for Yahoo OAuth information
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Key userkey = new KeyFactory.Builder(UserTable.class.getSimpleName(),user).getKey();
		UserTable a = pm.getObjectById(UserTable.class, userkey);
		String oauthdata = a.getAuthdata();

		QueryResult qr = null;

		try {
			qr = api.query2(query, oauthdata);
		} catch (OAuthException e) {
			return "Error posting to Y!:" + e.toString();
		} catch (RuntimeException e) {
			if (e.getMessage().equals("Unable to complete the HTTP request")) {
				if (e.getCause().getMessage()
						.contains("Timeout while fetching")) {
					return "Unable to complete Yahoo! query" + e.toString();
				} else {
					return "Error posting to Y!:" + e.toString();
					
				}
			} else {
				throw e;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Update token, if needed (for future requests)
	    if (qr != null && !qr.getAuthdata().equals(oauthdata)) {
	    	a.setAuthdata(qr.getAuthdata());
	    	try {
	    		pm.makePersistent(a);
	    	} finally {
	    		pm.close();
	    	}
	    }

		return qr.getText();
		
	}

	/**
	 * @param user the user to set
	 */
	public void setUser(String user) {
		this.user = user;
	}

	/**
	 * @return the user
	 */
	public String getUser() {
		return user;
	}

}
